<script lang="jsx">
import { defineComponent, h, computed } from "vue";
import { kebabCase } from "lodash-es";

import { getFieldConfig, resolveRuntimeComp } from "@/components/RuntimeComp";

const compMap = await resolveRuntimeComp();
const runtimeFormItemMap = Object.keys(compMap).reduce((map, compKey) => {
  map[kebabCase(compKey)] = {
    component: compMap[compKey].comp.default,
    props: { uiType: "Element" },
  };
  return map;
}, {});

export default defineComponent({
  inheritAttrs: false,
  props: {
    field: { type: Object, default: () => ({}) },
    modelValue: {
      type: [String, Boolean, Object, Array, undefined],
      default: "",
    },
    disabled: { type: Boolean, default: false },
  },
  emit: ["update:modelValue", "click"],
  setup(props, ctx) {
    const fieldConfig = getFieldConfig("Element");
    const formItmeMap = {
      ...fieldConfig,
      ...runtimeFormItemMap,
    };

    const fieldProps = computed(() => {
      return {
        ...componentType.value.props,
        ...props.field.props,
        placeholder: props.field.placeholder
          ? props.field.placeholder
          : (props.field.type.endsWith("select") ? "请选择" : "请输入") +
            props.field.label,
      };
    });

    const componentType = computed(() => {
      return (
        formItmeMap[props.field.type] ?? {
          component: {
            render() {
              return h("span", { style: { color: "red" } }, "暂未实现该组件");
            },
          },
          props: {},
        }
      );
    });

    const modeValue = computed({
      get() {
        return props.modelValue;
      },
      set(val) {
        console.log("modeValue", val);
        ctx.emit("update:modelValue", val);
      },
    });

    console.log("🚀 ~ setup ~ fieldProps.value:", fieldProps.value);
    return () => {
      // const { customerRender } = fieldProps.value;
      const Tag = componentType.value.component;
      const on = {
        onBlur: (...args) => {
          ctx.emit("blur", ...args);
          console.log("blur", ...args);
          const userBlur = fieldProps.value?.on?.blur;
          if (userBlur) {
            userBlur(...args);
          }
        },
        onChange: (...args) => {
          ctx.emit("change", ...args);
          console.log("change", ...args);
          const userChange = fieldProps.value?.on?.change;
          if (userChange) {
            userChange(...args);
          }
        },
        onClick: () => {
          ctx.emit("click");
        },
      };
      // TODO:双向绑定值有问题
      return (
        <Tag
          {...on}
          {...fieldProps.value}
          disabled={props.disabled}
          v-model:value={modeValue.value}
        />
      );
    };
  },
});
</script>
